package org.abettor.pushbox.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import org.abettor.android.ads.YoumiManager;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.map.Boxmap;
import org.abettor.pushbox.map.BoxmapUtil;
import org.abettor.pushbox.map.Step;
import org.abettor.pushbox.util.Statck;
import org.abettor.pushbox.view.PushBoxView;
import org.abettor.pushbox.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
//import android.widget.TableLayout;
import android.widget.TableLayout;

public abstract class AbstractPushBoxActivity extends Activity {
	protected Config.PushBoxConfig m_pushConfig;// 推箱子的各个配置
	protected Boxmap m_map;// 推箱子的地图
	protected LinearLayout m_pushBoxView;// 要显示图片的大小
	protected PushBoxView m_boxView;// 用来显示boxview
	protected Button m_up, m_left, m_down, m_right;// 用来操作上下左右的按钮
	protected Button m_restart, m_revert;// 重新开始,和上一步
//	private TableLayout m_tablePanel;// 菜单的panel
	protected final int PANNELHEIGHT = 145;
	protected Handler mHandler = new Handler();
	private final static long REDOTIME = 200;
	private final static long KEYDOWNTIME = 200;
	// 手势监听器
	protected GestureDetector.OnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() {
		boolean flag = false;// 标志位

		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			float x = e1.getX();
			float y = e1.getY();
			if (m_boxView.isScrollStartPointOnPerson(x, y)) {
				if (!flag) {
					shake(m_boxView);// 震动的操作
					float x2 = e2.getX();
					float y2 = e2.getY();
					flag = true;
					float tmpx = x2 - x, tmpy = y2 - y;
					if (tmpx > 0 && tmpy > 0) {// 想右滑的事件
						if (Math.abs(tmpx) > Math.abs(tmpy)) {
							moveright();
						} else {
							movedown();
						}
					} else if (tmpx > 0 && tmpy < 0) {
						if (Math.abs(tmpx) > Math.abs(tmpy)) {
							moveright();
						} else {
							moveup();
						}
					} else if (tmpx < 0 && tmpy > 0) {
						if (Math.abs(tmpx) > Math.abs(tmpy)) {
							moveleft();
						} else {
							movedown();
						}
					} else if (tmpx < 0 && tmpy < 0) {
						if (Math.abs(tmpx) > Math.abs(tmpy)) {
							moveleft();
						} else {
							moveup();
						}
					}
					// 回执flag的状态
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							flag = false;
						}
					}, REDOTIME);
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
	};
	private final int SHOW_AD = 13579;
	private YoumiManager youmi = new YoumiManager(this);
	private Handler youmiHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SHOW_AD) {
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 30) {
					youmi.showYoumi(YoumiManager.Position.middle, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};
	private Thread youmiDelayThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(200);
				Message msg = new Message();
				msg.what = SHOW_AD;
				youmiHandle.sendMessage(msg);
			} catch (InterruptedException e) {
				Log.d(this.getClass().getName(), "", e);
			}
		}
	};

	// 震动操作
	private void shake(View v) {
		if (AbstractPushBoxActivity.this.m_pushConfig.getShakeOn() == 1) {
			v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
					HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);// 触感反馈
		}
	}

	// 按钮点击的操作
	protected class ButtonOnTouchListener implements OnTouchListener {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				shake(v);
				if (v == m_up) {
					moveup();
				} else if (v == m_left) {
					moveleft();
				} else if (v == m_down) {
					movedown();
				} else if (v == m_right) {
					moveright();
				} else if (v == m_restart) {
					restart();
				} else if (v == m_revert) {
					revert();
				}
			}
			return true;
		}
	}

	// 读取各个配置
	private void readConfig() {
		m_pushConfig = Config.readPushBoxConfig(this);
	}

	// restart
	protected void restart() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog dialog = builder.create();
		dialog.setTitle(this.getText(R.string.confirm_restart_title));
		dialog.setMessage(this.getText(R.string.confirm_restart));
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, this
				.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						m_boxView.restartPush();
					}
				});
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE, this
				.getText(android.R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		dialog.show();
	}

	// revert
	protected void revert() {
		m_boxView.revertStep();
	}

	// move up
	protected void moveup() {
		m_boxView.up();
		checkState();
	}

	// move down
	protected void movedown() {
		m_boxView.down();
		checkState();
	}

	// move left
	protected void moveleft() {
		m_boxView.left();
		checkState();
	}

	// move right
	protected void moveright() {
		m_boxView.right();
		checkState();
	}
	//检查状态,判断地图是否已经完成
	protected void checkState(){
		//检查地图是否成功,成功的话
		if(m_boxView.checkIsSuccess()){
			Statck<Step> stack = m_boxView.getStackMap();
			byte [] buf = BoxmapUtil.paraStatckStepToArray(stack);
			try {
				writeFile(buf);
			} catch (IOException e) {
			}
			m_boxView.setHasCompleted(true);//设置状态,使其他键失效
			successOperation();//地图成功时的操作
		}
	}
	//写文件
	private void writeFile(byte[] buf) throws IOException{
		File file = null;
		file = new File(getStepFileName());
		FileOutputStream os = new FileOutputStream(file);
		os.write(buf);
		os.close();
	}
	protected abstract void successOperation();//地图成功时的操作
	protected abstract String getStepFileName();//获得地图步骤的文件名字
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.push_box_activity);
		m_pushBoxView = (LinearLayout) findViewById(R.id.push_box_view);
		m_boxView = (PushBoxView) findViewById(R.id.boxview);
		m_up = (Button) findViewById(R.id.button_up);
		m_up.setOnTouchListener(new ButtonOnTouchListener());
		m_left = (Button) findViewById(R.id.button_left);
		m_left.setOnTouchListener(new ButtonOnTouchListener());
		m_down = (Button) findViewById(R.id.button_down);
		m_down.setOnTouchListener(new ButtonOnTouchListener());
		m_right = (Button) findViewById(R.id.button_right);
		m_right.setOnTouchListener(new ButtonOnTouchListener());
//		m_tablePanel = (TableLayout) findViewById(R.id.pannel_id);
		m_revert = (Button) findViewById(R.id.button_revert);
		m_revert.setOnTouchListener(new ButtonOnTouchListener());
		m_restart = (Button) findViewById(R.id.button_restart);
		m_restart.setOnTouchListener(new ButtonOnTouchListener());
		// 读取各项配置信息
		readConfig();
		// 设置m_boxView
		initBoxMap();// 初始化地图
		initBoxView();
		// 重新设置界面的布局
		if (m_pushConfig.getFullScreenOn() == 0) {
			resetLayOut(false);
		} else {
			resetLayOut(true);
		}
		// 设置监听器
		m_boxView.setLongClickable(true);
		m_boxView.setOnTouchListener(new OnTouchListener() {
			GestureDetector mGestureDetector = new GestureDetector(
					AbstractPushBoxActivity.this, gestureListener);

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return mGestureDetector.onTouchEvent(event);
			}
		});
		youmiDelayThread.start();
	}

	// 重新设置layout
	private void resetLayOut(boolean full) {
		TableLayout layout = (TableLayout)this.findViewById(R.id.pannel_id);
		if (!full) {// 非全屏
			layout.setVisibility(View.VISIBLE);
		} else {// 全屏的操作
			layout.setVisibility(View.GONE);
		}
	}

	// 读取屏幕宽度
	@SuppressWarnings("unused")
	private int readScreenWidth() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		return display.getWidth();
	}

	// 读取屏幕高度
	@SuppressWarnings("unused")
	private int readScreenHeight() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		return display.getHeight();
	}

	// 初始化地图
	private void initBoxMap() {
		m_map = initTheBoxMap();
	}
	protected abstract Boxmap initTheBoxMap();

	private void initBoxView() {
		m_boxView.setMap(m_map);
	}
	// 进行全屏的操作
	protected void fullScreen() {
		if (m_pushConfig.getFullScreenOn() == 0) {
			resetLayOut(true);
			m_pushConfig.setFullScreenOn(1);
		} else {
			resetLayOut(false);
			m_pushConfig.setFullScreenOn(0);
		}
		Config.savePushBoxConfig(this, m_pushConfig);
	}

	// 打开或关闭按键反馈的操作
	protected void onShock() {
		if (m_pushConfig.getShakeOn() == 0) {
			m_pushConfig.setShakeOn(1);
		} else {
			m_pushConfig.setShakeOn(0);
		}
		Config.savePushBoxConfig(this, m_pushConfig);
	}

	private boolean keydownflag = false;

	/**
	 * 捕获按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keydownflag) {
			return super.onKeyDown(keyCode, event);
		}
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
			fullScreen();
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			moveleft();
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			moveright();
			break;
		case KeyEvent.KEYCODE_DPAD_UP:
			moveup();
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			movedown();
			break;
		}
		keydownflag = true;
		// this.m_boxView.requestFocus();
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				keydownflag = false;
			}
		}, KEYDOWNTIME);
		return super.onKeyDown(keyCode, event);
	}
	/**
	 * 把文件读成二进制数组
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	protected byte [] readFileByPath(String filename) throws IOException{
		File file = new File(filename);
		if(!file.exists()){
			return null;
		}
		InputStream in = new FileInputStream(file);
		ByteArrayOutputStream byteout = new ByteArrayOutputStream();
		int value = 0;
		while((value = in.read())!=-1){
			byteout.write(value);
		}
		return byteout.toByteArray();
	}
}
